import * as React from 'react';
import { Icon } from 'antd';
import makeHoc from 'components/common/makeHoc';
import CONFIG from 'constants/config';

import LoadableComponent from 'components/common/LoadableComponent';
const LoadablePopAudioSelect = LoadableComponent(() => import('pages/attachment/PopToSelect'));
const LoadableMedia = LoadableComponent(() => import('components/common/Media'));

interface EditAudioProps {
  dispatch: (action: any) => any;
  handleCallback: (audio: any) => any;
  loading: boolean;
  selectedItems: any[];
  audio: any;
}

interface EditAudioState {
  isSelectAudio: boolean;
}
class EditAudio extends React.Component<EditAudioProps, EditAudioState> {
  static defaultProps: EditAudioProps = {
    dispatch: () => {},
    handleCallback: () => {},
    loading: false,
    selectedItems: [],
    audio: null,
  };
  constructor(props: EditAudioProps) {
    super(props);
    this.state = {
      isSelectAudio: false,
    };
  }

  handleRemoveAudio = () => {
    this.props.handleCallback(null);
  };

  handleSubmit = () => {
    const { selectedItems, handleCallback } = this.props;
    handleCallback(selectedItems[0]);
    this.handleCloseModal();
  };

  handleCloseModal = () => {
    this.setState({
      isSelectAudio: false,
    });
  };

  handleOpenModal = () => {
    this.setState({
      isSelectAudio: true,
    });
  };

  renderItems = () => {
    const { audio } = this.props;
    if (!audio) {
      return (
        <p className="loading-placeholder">
          还没有数据，&nbsp;
          <a href="javascript:void(0);" onClick={this.handleOpenModal}>
            <Icon type="plus" />添加
          </a>
        </p>
      );
    }

    return (
      <LoadableMedia
        attachment={audio}
        onDestroy={() => {
          this.handleRemoveAudio();
        }}
        isTiny={false}
      />
    );
  };

  render() {
    return (
      <div>
        {this.state.isSelectAudio && (
          <LoadablePopAudioSelect
            selectType={CONFIG.ITEM_AUDIO}
            onCancel={this.handleCloseModal}
            onOk={this.handleSubmit}
            selectMax={1}
          />
        )}
        {this.renderItems()}
      </div>
    );
  }
}

interface OwnProps {
  audio: any;
  handleCallback: (audio: any) => any;
}

function mapStateToProps(state: any, ownProps: OwnProps) {
  const { selectedItems, loading } = state.attachment;
  const { audio, handleCallback } = ownProps;
  return {
    audio,
    loading,
    selectedItems,
    handleCallback,
  };
}

export default makeHoc(mapStateToProps)(EditAudio, {
  addAudio() {
    this.handleOpenModal();
  },
});
